package com.example.disk.controller;


import com.example.disk.domain.FileDTO;
import com.example.disk.domain.entity.File;
import com.example.disk.service.FileService;
import com.example.disk.service.UserService;
import com.example.disk.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LPC
 * @since 2020-07-15
 */
@Controller
@RequestMapping("/file")
@ResponseBody
public class FileController {

    @Autowired
    FileService fileService;
    @Autowired
    UserService userService;

    /*
    * 测试成功
    * */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Response getFileList(@RequestParam("filepath")  String filepath, HttpSession session) throws IOException {
        String username = (String)session.getAttribute("username");
        return Response.build()
                .setCode(200)
                .setData(fileService.getFileList(username, filepath));
    }

    /**
     *测试:成功
     */
    @RequestMapping(value = "/listbytype", method = RequestMethod.GET)
    public Response getFileListByType(@RequestParam("filetype")  String filetype, HttpSession session) throws IOException {
        String username = (String)session.getAttribute("username");
        int intFileType = Integer.parseInt(filetype);
        return Response.build()
                .setCode(200)
                .setData(fileService.getFileListByType(username, intFileType));
    }

    /*
    * 测试：成功
    * */
    @RequestMapping(value = "/storage", method = RequestMethod.GET)
    public Response getStorage(HttpSession session) {
        int userId = (int)session.getAttribute("userId");
        Map<String,Integer> data = new HashMap<>();
        data.put("used",userService.getUsedSize(userId));
        data.put("total",userService.getTotalSize(userId));
        return Response.build().setCode(200).setData(data);
    }

    @RequestMapping("/upload")
    public Response upload(@RequestParam("filepath") String path,
                           @RequestParam("isdir") Integer isDir,
                           HttpSession session,
                           MultipartFile file) throws IOException {
        String username = (String)session.getAttribute("username");
        if (fileService.saveFile(username, path, file, file.getOriginalFilename()))
            return Response.build().setCode(200).setMsg("上传成功");
        return Response.build().setCode(500).setMsg("上传失败");
    }

    @RequestMapping(value = "/delete")
    public Response deleteFile(@RequestParam("filename") String fileName,
                               @RequestParam("filepath") String path,
                               @RequestParam("extendname") String extend,
                               @RequestParam("filesize") String fileSize,
                               @RequestParam("isdir") Integer Dir,
                               @RequestParam("uploadtime") String createTime,
                               HttpSession session) {
        String username = (String)session.getAttribute("username");
        if(Dir==1){ //删除文件夹
            if (fileService.deleteDir(username, path, fileName))
                return Response.build().setCode(200).setMsg("删除成功");
            return Response.build().setCode(500).setMsg("删除失败");
        }else{  //删除文件
            if (fileService.deleteFile(username, path, fileName, extend))
                return Response.build().setCode(200).setMsg("删除成功");
            return Response.build().setCode(500).setMsg("删除失败");
        }
    }

    @RequestMapping(value = "/batchdeletefile", method = RequestMethod.POST)
    public Response batchDelete(@RequestBody FileDTO[] files, HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (fileService.batchDeleteFile(username, files))
            return Response.build().setCode(200).setMsg("删除成功");
        return Response.build().setCode(500).setMsg("删除失败");
    }

    @RequestMapping("/createdir")
    public Response createDir(String filepath, String filename,HttpSession session){
        String name = filename.trim();
        if(name.equals("")) return Response.build().setCode(400).setMsg("文件名不能为空");
        String username = session.getAttribute("username").toString();
        boolean flag= fileService.createDir(username,filepath,name);
        if(flag){
            return Response.build().setCode(200).setMsg("创建成功");
        }else{
            return Response.build().setCode(400).setMsg("创建失败");
        }
    }

    @RequestMapping("/search")
    public Response search(HttpSession session,String filename) throws IOException {
        String username = session.getAttribute("username").toString();
        int user_id =(int)session.getAttribute("userId");
        if(filename.equals("")){
            return Response.build().setCode(200).setMsg("找到了").setData(fileService.getFileList(username,"/"));
        }
        return Response.build().setCode(200).setMsg("找到了").setData(fileService.searchByName(username,user_id,filename));
    }

    //得到文件树
    @RequestMapping("/tree")
    public Response getDirtree(HttpSession session){
        String username = session.getAttribute("username").toString();
        Object data = fileService.getDirTree(username);

        if(data==null){
            return Response.build().setMsg("没找到数据").setCode(200);
        }else{
            return Response.build().setMsg("找到数据").setCode(200).setData(data);
        }
    }


    @RequestMapping("/download")
    public String downloadFile(HttpServletResponse response, HttpSession session, String filepath, String filename, String extendname) throws IOException {
        String name = filename+"." + extendname;
        String username = session.getAttribute("username").toString();
        if (name != null) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + name);// 设置文件名
                byte[] buffer = new byte[1024];
                InputStream is=null;
                try {
                    is = fileService.getInputStream(username,filepath,name);
                    OutputStream os = response.getOutputStream();
                    int i = is.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = is.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
        }
        return "下载失败";
    }

    //移动文件夹
    @RequestMapping("/move")
    public Response move(HttpSession session,String oldfilepath,String id,String filename,String extendname) throws IOException {
        String username = session.getAttribute("username").toString();
        System.out.println("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhh  "+extendname);
        boolean flag = fileService.moveFile(username,oldfilepath,filename,extendname,Integer.parseInt(id));
        if(flag){
            return Response.build().setCode(200).setMsg("移动成功");
        }else{
            return Response.build().setCode(400).setMsg("移动失败");
        }

    }

//    @RequestMapping("/batchmove")
//    public Response batchmove(HttpSession session,String id){
//        File aim_dir=fileService.getFileById(Integer.parseInt(id));     //目的地址
//        if(file.getFlag()==0){      //文件
//
//        }else{  //文件夹
//
//        }
//        return null;
//    }

}
